﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using chihuopig.Web.Framework;
using Microsoft.AspNetCore.Session;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Caching.Redis;
using StackExchange.Redis;
using Microsoft.AspNetCore.Http;
using System.Reflection;
using Autofac.Extensions.DependencyInjection;
using Autofac;
using Microsoft.Extensions.Logging;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Extensions.Logging;
using NLog.Web;
using SqlSugar;
using chihuopig.Service;
using Microsoft.Extensions.FileProviders;

namespace chihuopig.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
       // public static ILoggerRepository repository { get; set; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //services.AddSignalR();
            services.AddSession(s=>
            {
                s.IdleTimeout=TimeSpan.FromHours(20);
            });
           /* repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));*/
            //string redisConn = Configuration.GetConnectionString("RedisConfig");
            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("118.89.50.208:6379");
            services.AddSingleton<IDatabase>(redis.GetDatabase());
            services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
            //依赖注入
            //services.AddSingleton<SqlSugarClient>(new SqlSugarClient(new ConnectionConfig() { DbType = DbType.MySql, ConnectionString = Configuration.GetConnectionString("SqlConnectConfig") }));
            services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Test-Keys");//127.0.0.1 118.89.50.208
            string SqlConnect = Configuration.GetConnectionString("SqlConnectConfig");
            // Enyim.Caching.Configuration.configurationgg
            services.AddInstance(()=>{
                return DBService.getInstance("database=chihuopig;server=127.0.0.1;port=3306;user id=root;pwd=root;charset=utf8",
                new List<SlaveConnectionConfig>()
                {
                    new SlaveConnectionConfig(){ HitRate=10, ConnectionString="database=chihuopig;server=127.0.0.1;port=3316;user id=root;pwd=root;charset=utf8" }
                });
            });


            //services.AddDistributedRedisCache(e => {
            //    e.Configuration = redisConn;
            //    e.InstanceName = Configuration.GetConnectionString("Redis_Session");
            //});
          
            //services.AddEnyimMemcached(s=>
            //{
            //    string Address= Configuration.GetConnectionString("MemcachedConfig");
            //    s.AddServer(Address.Split(':')[0],Convert.ToInt32(Address.Split(':')[1]));
            //});
            //全区过滤器
            services.AddMvc(filter=> 
            {
               filter.Filters.Add(new MyException());
            });
            //*****************Mongo的连接配置****************
            /*MongoClient d = new MongoClient();
            services.AddSingleton<IMongoDatabase>(d.GetDatabase(""));*/
            services.AddDirectoryBrowser();
            //auto.factnci
            var containerBuilder = new ContainerBuilder();
            //containerBuilder.RegisterAssemblyTypes(Assembly.Load("chihuopig.Service")).Where(c=>c.);
            containerBuilder.RegisterAssemblyTypes(Assembly.Load("chihuopig.Service"))
                .AsImplementedInterfaces();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();
            return new AutofacServiceProvider(container);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
        {
            /* app.UseSignalR(routes => {
                        fdsfdsfdsfds
                 routes.MapHub<Chat>("/chat");
             });*/
            app.UseSession();
            env.ConfigureNLog(Path.Combine(Directory.GetCurrentDirectory(), "nlog.config"));
            loggerFactory.AddNLog();
            //添加NLog到.net core框架中

            //添加NLog的中间件
            // app.use
            //指定NLog的配置文件
            //app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            //{
            //    FileProvider = new PhysicalFileProvider(
            //      Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "img")),
            //    RequestPath = new PathString("/img")
            //});
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Web/Home/Error");
            }
            app.UseStaticFiles();
           
            //app.UseEnyimMemcached();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "defaulstml",
                  template: "{html=html}/{platform=Web}/{controller=Home}/{action=Index}/{id}.shtml");

                routes.MapRoute(
                    name: "default",
                    template: "{platform=Web}/{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
